package stu.day25_day32.day26;
import stu.day25_day32.day25.all.*;

import java.util.ArrayList;
import java.util.List;

public class hw1 {

    public boolean isUnivalTree(TreeNode root) {
        return isU(root,root.val);
    }
    public boolean isU(TreeNode node,int num){
        if(node==null){
            return true;
        }
        if(node.val!=num){
            return false;
        }
        return isU(node.right,num)&&isU(node.left,num);
    }



    public List<String> binaryTreePaths(TreeNode root) {

        List<String> str = new ArrayList<>();
        List<List<Integer>> list = aList(root);

        if(list.size()==0){
            return str;
        }

        for(int i=0;i<list.size();i++){
            List<Integer> l1 = list.get(i);
            int index = 0;
            StringBuilder sj = new StringBuilder();
            if(l1.size()>0){
                for (Integer num :l1){
                    if(index==0){
                        sj.append(num);
                        index+=1;
                    }else {
                        sj.append("->");
                        sj.append(num);
                    }
                }
                str.add(sj.toString());
            }
        }

        return str;



    }

    public List<List<Integer>> aList(TreeNode node){
        List<List<Integer>> list = new ArrayList<>();
        if(node==null){
            return list;
        }

        List<List<Integer>> left = aList(node.left);
        List<List<Integer>> right = aList(node.right);

        if(left.size()==0&&right.size()==0){
            List<Integer> l1 = new ArrayList<>();
            l1.addFirst(node.val);
            list.add(l1);
            return list;
        }


        for(int i=0;i<left.size();i++){
           List<Integer> l1 = left.get(i);
           l1.addFirst(node.val);
           list.add(l1);
        }

        for(int i=0;i<right.size();i++){
            List<Integer> l1 = right.get(i);
            l1.addFirst(node.val);
            list.add(l1);
        }

        return list;
    }

    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        List<List<Integer>> list = new ArrayList<>();
        List<Integer> l = new ArrayList<>();
        aList(root,targetSum,0,list,l);
        return list;
    }

    public void aList(TreeNode node,int targetSum,int sum,List<List<Integer>> list,List<Integer> l){
        if(node==null){
            return;
        }
        sum += node.val;
        l.add(node.val);
        if(node.left==null&&node.right==null&&(sum==targetSum)){
            list.add(l);
            return;
        }
        aList(node.left,targetSum,sum,list,l);
        aList(node.right,targetSum,sum,list,l);
        l.removeLast();
        return;
    }



}
